package com.zj.leetcode.easy.tree;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: algorithm
 * @description: 二叉搜索树的最小绝对差
 * 530 minimum-absolute-difference-in-bst
 * @author: Zhang Bo
 * @create: 2022-07-06 15:54:33
 **/
public class MinimumAbsoluteDifferenceInBst {
    public static void main(String[] args) {
        Solution solution = new MinimumAbsoluteDifferenceInBst().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        List<Integer> list = new ArrayList<>();

        public int getMinimumDifference(TreeNode root) {
            if (root == null) {
                return 0;
            }
            this.dfs(root);
            int min = Integer.MAX_VALUE;
            for (int i = 0; i < list.size() - 1; i++) {
                for (int j = i + 1; j < list.size(); j++) {
                    int sub = Math.abs(list.get(i) - list.get(j));
                    min = Math.min(min, sub);
                }
            }
            return min;
        }

        public void dfs(TreeNode node) {
            if (node != null) {
                list.add(node.val);
                if (node.left != null) {
                    this.dfs(node.left);
                }
                if (node.right != null) {
                    this.dfs(node.right);
                }
            }
        }

        List<Integer> ret = new ArrayList<>();

        /**
         * 因为是搜索二叉树，左子树小，右子树大，父节点中间
         * 所以中序遍历是升序呀！！！！
         *
         * @param root
         * @return
         */
        public int getMinimumDifference02(TreeNode root) {
            if (root == null) {
                return 0;
            }
            this.dfs02(root);

            int min = Integer.MAX_VALUE;
            System.out.println(Arrays.toString(ret.toArray()));
            for (int i = 1; i < ret.size(); i++) {
                min = Math.min(min, ret.get(i) - ret.get(i - 1));
            }
            return min;
        }

        public void dfs02(TreeNode node) {
            if (node != null) {
                if (node.left != null) {
                    this.dfs02(node.left);
                }
                ret.add(node.val);
                if (node.right != null) {
                    this.dfs02(node.right);
                }
            }
        }

    }
//leetcode submit region end(Prohibit modification and deletion)

}

